<template>
	<view class="content">
		<view>
			
			<view class="dingwei">
				<view 
				@touchstart="handleTouchStart('top')" 
				@touchend="handleTouchEnd('stop')"
				class="upper">上</view>
				<view 
				@touchstart="handleTouchStart('right')"
				@touchend="handleTouchEnd('stop')"
				class="right">右</view>
				
				<view 
				@touchstart="handleTouchStart('down')"
				@touchend="handleTouchEnd('stop')"
				class="lower">下</view>
				<view 
				@touchstart="handleTouchStart('left')"
				@touchend="handleTouchEnd('stop')"
				class="left">左</view>
				
				<view 
				@tap="bb('catch')" 
				class="grab">抓</view>
				
				<view @tap="bb('start')" class="start">游戏开始</view>
				<view @tap="bb('stop')" class="start" style="top: -50px;">暂停</view>
				
				<view @tap="bb('connect')" class="connect">链接娃娃机</view>
			</view>
			
		</view>
	</view>
</template>

<script>
	import {
		request
	} from "@/static/common.js";
	export default {
		data() {
			return {
				pagenum: 1,
				currentIndex: 1,
				transformX: 0,
				list: [],
				pagetnum: '', //总条数
				totalnum: '', //总页数
				showspin: true, //加载
				meiyoushuju: false,
				ldata: false,
				statuscodevalue: 0,
				popup: false, //弹窗
				ids: '',
				explainvalue: '不通过',
				button2index: "",
				deletevauel: false,
				ids: [],
				findid: '', //搜素创作者
				uid:'',
				commodity_id:"",
				count:"",//人数
				name:"",//娃娃机名称
				codeTime: 0, //倒计时
				timer:null,
				xintimer:null,//心跳
				xincodeTime: 0, //倒计时
			}
		},

		onLoad(option) {
			
			 
			console.log('参数1:', option); // 输出 value1
			this.commodity_id = option.id
			this.getmachine()
		},
		
		onUnload() {
		    this.destroyCountdown();
		  },

		methods: {
			
			
			async getmachine(e) {
				let apply = await request(`${getApp().globalData.http}commodity/get_machine`, {
					'X-Requested-With': 'XMLHttpRequest',
					'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
				}, "GET", {
					commodity_id: this.commodity_id,
				})
				if (apply.data.code == 0) {
					  console.log('哇哇》》',apply.data.data)
					  this.count = apply.data.data[0].count
					  this.name = apply.data.data[0].name
					  this.connectSocket()
				} else {
					uni.showToast({
						title: `${apply.data.message}`,
						icon: "none",
					})
				}
			},
			 
			    handleTouchEnd(text) {
			      // 松开事件处理
			      console.log('松开事件处理', text);
				  let data = {
				  	'direction':text
				  }
				  
				  
				  this.sendSocketMessage(JSON.stringify(data))
			    },
			handleTouchStart(text){
				console.log('按下事件处理', text);
				let data = {
					'direction':text
				}
				 
				
				this.sendSocketMessage(JSON.stringify(data))
			},
			bb(text){
				
					var data = ""
					// 游戏开始
					if(text == 'start'){
						  data = {
							'direction':text,
							}
							clearInterval(this.timer)
						}else if(text == 'catch'){
							// 抓
							data = {
								'direction':text
							}
						}else if(text == 'connect'){
							// 链接娃娃机
							data = {
								'direction':text
							}
						}else if(text == 'stop'){
							// 链接娃娃机
							data = {
								'direction':text
							}
						}
					
					
					
					
				    		
						this.sendSocketMessage(JSON.stringify(data))
					
			},
				
		
			//连接websocket
			connectSocket() {
							let that = this;
							console.log('调用连接websocket')
							var token = getApp().globalData.token
							this.socketTask = uni.connectSocket({
								
								    // url: 'ws://120.55.52.136:9090/ws/connect/TestConsumer',
									// url: 'ws://120.55.52.136:9090/ws/connect/user/'+that.uid+'/',
									// url: 'ws://120.55.52.136:9090/ws/user/XlclZ1ZVUU4xX3VzZXI=/4/t001/',
									url: 'ws://120.55.52.136:9090/ws/user/'+token+'/'+this.commodity_id+'/'+this.name+'/',
								
									header: {  
									            Authorization:2,  
									        },
									success(res) {
										that.heart()
										console.log("websocket连接成功");
										// that.isSuccess = true
									},
									fail(err) {
										console.log("报错", err);
									}
								},
			 
			 
							);
						
							that.socketTask.onMessage(function(res) {
								var data = JSON.parse(res.data)
								
								console.log('2收到服务器内容：' ,typeof data);
								console.log('3收到服务器内容' ,data);
								if(data.code == '0'){
									
									
									// if(data.message == 'ready'){
									// 	// that.socketTask.close()
									// 	// 防止重复获取
									// 	if (that.codeTime > 0) {
									// 		return
									// 	}
									// 	// 倒计时
									// 	that.codeTime = 10
									// 	// 箭头函数可以直接拿到外面的this的内容
									// 	that.timer = setInterval(() => {
									// 		if (that.codeTime >= 1) {
									// 			that.codeTime--
									// 			that.codeTime = that.codeTime
									// 			console.log('倒计时1',that.codeTime)
									// 		} else {
									// 			that.socketTask.close()
									// 			console.log('倒计时2')
									// 			clearInterval(that.timer)
									// 		}
									// 	}, 1000)
									// }else if(data.message == '游戏结束清重新开始'){
									// 	that.socketTask.close()
									// }
									
									
								}
								// that.handlerMsg(JSON.parse(res.data)) //这里是对获取到的数据进行操作
							});
			 
			 
						},
			
			//发送消息
				sendSocketMessage(msg) {
							console.log('发送信息')
							
							console.log(msg)
							let that = this;
							return new Promise((reslove, reject) => {
								that.socketTask.send({
									data: msg,
									success(res) {
										console.log('发送成功')
										reslove(res)
									},
									fail(res) {
										console.log('发送失败')
										console.log(res)
										// reject(res)
									}
								});
							})
			 
						},
						
						//返回上个页面关闭ws
						destroyCountdown() {
						      // clearInterval(this.timer)
							  clearInterval(this.xintimer)
						      this.codeTime = 0;
							  this.timer = null
							  this.xintimer = null
						    },
						
			//心跳
						heart() {
							let that = this;
							clearInterval(this.xintimer);
							this.xintimer = '';
							let msg = {
								"direction": "active",
							}
							this.xintimer = setInterval(() => {
								 that.sendSocketMessage(JSON.stringify(msg)).then(res => {
									console.log('心跳成功')
								}).catch(res => {
									console.log('发送失败')
								console.log((res))
								 })
			 
							}, 10000)
						},	
			
		},

	}
</script>

<style>
	.dingwei{
		width: 100%;
		height: 800rpx;
		position: relative;
		top: 300rpx;
		text-align: center;
		line-height: 100rpx;
	}
	.upper{
		position: absolute;
		width: 100rpx;
		height: 100rpx;
		background: yellow;
		left: 180rpx;
		
	}
	.right{
		position: absolute;
		width: 100rpx;
		height: 100rpx;
		background: yellow;
		left: 300rpx;
		top: 100rpx;
	}
	.lower{
		position: absolute;
		width: 100rpx;
		height: 100rpx;
		background: yellow;
		left: 180rpx;
		top: 200rpx;
	}
	
	.left{
		position: absolute;
		width: 100rpx;
		height: 100rpx;
		background: yellow;
		left: 62rpx;
		top: 100rpx;
	}
	
	.grab{
		position: absolute;
		width: 100rpx;
		height: 100rpx;
		background: yellow;
		right: 100rpx;
		top: 100rpx;
	}
	
	.start{
		position: absolute;
		width: 200rpx;
		height: 100rpx;
		background: yellow;
		left: 300rpx;
		bottom: 0rpx;
	}
	.connect{
		position: absolute;
		width: 200rpx;
		height: 100rpx;
		background: yellow;
		left: 300rpx;
		bottom: -300rpx;
	}

</style>
